package com.example.tool.conf;

import cn.hutool.core.util.ObjectUtil;
import com.example.tool.bean.business.WarehouseConfigEntity;
import com.example.tool.bean.business.WarehouseExpressDeliveryConfig;
import com.example.tool.bean.business.WarehouseInterceptionConfig;
import com.example.tool.erp.sdk.api.wms.stockout.dto.SalesStockoutResponse;
import com.example.tool.service.RedisService;
import com.example.tool.util.DDUtil;
import com.example.tool.util.DateUtil;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import com.example.tool.util.WDTUtil;
import com.example.tool.util.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.example.tool.erp.sdk.api.wms.stockout.dto.SalesStockoutRequest.STATUS_TYPE_CONSIGNED;
import static com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil.UNKNOWN;
import static com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil.judgeExpressDeliveryType;

/**
 * 订单拦截任务
 */
@Component
public class PDDTasks {
    @Autowired
    private RedisService redisService;
    private static final String ddLinkUrl = "https://alidocs.dingtalk.com/i/nodes/%s";
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter FORMATTER_YYYY_MM = DateTimeFormatter.ofPattern("yyyy-MM");
    private static final String keyTemplate = "sys:interceptWorkbookId:%s:%s";
    private static final String warehouseRangeAddressTemplate = "A%s:G%s";
    private static final String warehouseMsgTitle = "订单未发仓内拦截通知-测试阶段";
    private static final List<String> warehouseHeaderValues = Arrays.asList("原始单号", "出库单号", "订单编号", "物流单号", "创建时间", "发货时间", "揽收时间");
    private static final String warehouseMsgTemplate = "原始单号：%s\n出库单号：%s\n订单编号：%s\n物流单号：%s\n创建时间：%s\n发货时间：%s\n揽收时间：%s";
    private static final String warehouseEndingContent = "处理类型：订单未发运，终止出库，退换单请及时入库。";
    private static final String expressDeliveryRangeAddressTemplate = "A%s:D%s";
    private static final String expressDeliveryMsgTitle = "退款在途拦截-测试阶段";
    private static final List<String> expressDeliveryHeaderValues = Arrays.asList("原始单号", "出库单号", "订单编号", "物流单号");
    private static final String expressDeliveryMsgTemplate = "原始单号：%s\n出库单号：%s\n订单编号：%s\n物流单号：%s";
    private static final String expressDeliveryEndingContent = "处理类型：拦截退回";
    //    private static final String sheetIdPrefix="订单拦截统计表";
//    private static final String sheetId="订单拦截统计表";
    private static final Integer readBatchSize = 3000;
    private static final Integer updateBatchSize = 3000;
    private static final String INTERCEPTION = "库内拦截";
    private static final String INTERCEPT = "在途拦截";
    //常温
    private static final String roomTemperatureType = "1";
    //冻品
    private static final String frozenProductsType = "2";
    //    //已发货
//    private static final  String shippedStatus="110";
    //待发货
    private static final List<Integer> reviewedStatus = Arrays.asList(-1, 10, 50, 51, 52, 53, 54, 58, 60, 61, 63, 65, 70, 73, 75, 77, 79);
    //已发货
    private static final List<Integer> shippedStatus = Arrays.asList(90, 110);
    //查询状态出库单状态
    /**
     * 出库单状态:
     * 10待放回(拣货待放回), 小于该值的都是已取消的单子
     * 50待审核
     * 51缺货
     * 52缺货待入库
     * 53 WMS已接单
     * 54 获取电子面单
     * 58 档口锁定
     * 60 待分配
     * 61 排队中
     * 63 待补货
     * 65 待处理
     * 70 待发货
     * 73 爆款锁定
     * 75 待拣货
     * 77 拣货中,PDA拣货后
     * 79 已拣货
     * 90 延时发货
     * 110已完成
     * -1未发货
     */
    private static final String findStatus = "-1,10,50,51,52,53,54,58,60,61,63,65,70,73,75,77,79,90,110";
    //定时间隔单位分钟
    private static final long intervalTime = 10L;
    //几点开始
    private static final Integer startIntervalTime = 8;
    //保存时间值
    private static final Integer dataSaveDays = 7;
    //保存时间的单位
    private static final TimeUnit timeUnit = TimeUnit.DAYS;
    //仓库参数
    public static HashMap<String, WarehouseConfigEntity> WAREHOUSE_INTERCEPT_CONFIG = new HashMap<>();

    static {
        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.LG_CW.getCode(),//苍南-龙港（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.LG_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//龙港仓（常温）审单对接群
                                "YndMj49yWjmvkeaxi0ZdjB6M83pmz5aA",
//    "14lgGw3P8vLlreAgtdKL6qb9V5daZ90D",
                                WarehouseMsgSDConfEnum.LG_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.LG_CW_SD.getToken(),
//    "SEC19af71dcdb6f679f375de58a69a74dd66d723df30ea6bd6e5fd3d2aba86e8208",
//    "80e2322d737f724c603f6157168246ab6883e0713cc705646bb52d336b6df3e3",
                                null, null)
                        , Arrays.asList(
                        new WarehouseExpressDeliveryConfig(//龙港仓（常温）快递售后群（申通）
//    ExpressDeliveryUtil.STO,
//    1,
                                WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getPlatform(),
                                "Qnp9zOoBVBezpxbnFG4EdXYkW1DK0g6l",
                                WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getSecret(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_SOT.getToken(),
//    "SEC3530451e3910a9de749c955ab402b2a23d029da3aff72b0e91944f4ffea29901",
//    "3be4f4c7c52fed6d3438909cc938ac19d2a79ecc40a09563318b87cd03752b73",
                                null, null)
                        , new WarehouseExpressDeliveryConfig(//龙港中通
                                WarehouseMsgKDConfEnum.LG_CW_KD_ZTO.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_ZTO.getPlatform(),
//    ExpressDeliveryUtil.ZTO,
//    2,
                                "dcs8N3YnSkv8s--L4oQQD_Blv4qQeN8em4iFizYma4-PccrSDe3citeMUH5RC7VKXY9YqeMWI2iwee9ZnW64gWTQ",
                                WarehouseMsgKDConfEnum.LG_CW_KD_ZTO.getSecret(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_ZTO.getToken(),
//    "testchat123",
//    "",
                                null, null)
                        , new WarehouseExpressDeliveryConfig(//龙港极兔
                                WarehouseMsgKDConfEnum.LG_CW_KD_JT.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_JT.getPlatform(),
//    JT,
//    2,
                                "dc9WLZmBkJKeHzgfx0Dc_7J8XBo-l_vx_PejgLqjtNXfO34wdNPwBYh-lzyd_IuePadG3HIhHZbCdMgtl3PxJZqA",
                                WarehouseMsgKDConfEnum.LG_CW_KD_JT.getSecret(),
                                WarehouseMsgKDConfEnum.LG_CW_KD_JT.getToken(),
//  "JGJTGroupChat",
//    "",
                                null, null)
                )
                )
        );


        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CQ_DP.getCode(), //重庆-中通（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CQ_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//重庆仓（冻品）审单对接群
                                "vy20BglGWOMOykAqTlkB1mAPJA7depqY",
                                WarehouseMsgSDConfEnum.CQ_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CQ_DP_SD.getToken(),
//    "SEC5c0852177e757940afaaecad5fd0ddd55f653c299bad9a6d5204e81752788afe",
//    "b665f561ffd7755dfb003b82d2446b6e5ddafecc3b213e4db8a04da9799b3067",
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//重庆仓（冻品）快递售后群
                                WarehouseMsgKDConfEnum.CQ_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.CQ_DP_KD.getPlatform(),
                                "kDnRL6jAJMDAYjEwHD7zbnbaVyMoPYe1",
                                WarehouseMsgKDConfEnum.CQ_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.CQ_DP_KD.getToken(),
//    "SEC96bf424e75957b1940ade52514036b1facbd09eafd5ca7edbf1fbbcc471a89c6",
//    "933590ef48062a42b7906a8fd876b7782df3910c47a23534f31ac16ec88dc735",

                                null, null)))

        );

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.JG_CW.getCode(), //广州-江高（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.JG_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//江高仓（常温）审单对接群
                                "2Amq4vjg89eqvP2NFdlokpw483kdP0wQ",
                                WarehouseMsgSDConfEnum.JG_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.JG_CW_SD.getToken(),
//    "SEC71886d7de0e913186f1c34b796a5f8381b29537f327d3da2977b24d590c69a54",
//    "939653f7533235b20bb6f47b49517587c43c838f78de8f776e041f07eefdd8b3",

                                null, null),
                        Arrays.asList(
                                new WarehouseExpressDeliveryConfig(//江高仓（常温）快递售后群（圆通）
//    YTO,
//    1,
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YTO.getExpressDeliveryType(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YTO.getPlatform(),
                                        "20eMKjyp81ONekDKudwzB3GvVxAZB1Gv",
//    "SECda76372127b3a91fc2d76aed4872c7caa3c31028352c7e9876c48797ba5d1ad1",
//    "f45c82911719da8d29fc5164b4c2588e51e0d68b278d116b4fbd8cb2dc63fa50",
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YTO.getSecret(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YTO.getToken(),
                                        null, null)
                                , new WarehouseExpressDeliveryConfig(//江高中通快递对接
                                        WarehouseMsgKDConfEnum.JG_CW_KD_ZTO.getExpressDeliveryType(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_ZTO.getPlatform(),
//    ZTO,
//    2,
                                        "dcJ0Pwc7k1zsiYOygwlSGxipX0rGz43g-ISqV_YIHfPonkkYBM_vutaBMJbUYi-42xD5FtUED7zzURYjoKA0pdNw",
//    "JGZTGroupChat",
//    "",
                                        WarehouseMsgKDConfEnum.JG_CW_KD_ZTO.getSecret(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_ZTO.getToken(),
                                        null, null)
                                , new WarehouseExpressDeliveryConfig(//忆北江高极兔
                                        WarehouseMsgKDConfEnum.JG_CW_KD_JT.getExpressDeliveryType(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_JT.getPlatform(),
//    JT,
//    2,
                                        "dcMbmjKY-pT5R2pfWChZ3Nicgk-5vMI1ok9yWsTPHDg513juX3kEoWtsOl8it0TC4xbE7mGsMrQk4sK_PUj6VRVw",
//    "JTJGGroupChat",
//    "",
                                        WarehouseMsgKDConfEnum.JG_CW_KD_JT.getSecret(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_JT.getToken(),
                                        null, null)
                                , new WarehouseExpressDeliveryConfig(//江高 广东 韵达
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YUN_DA.getExpressDeliveryType(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YUN_DA.getPlatform(),
//    YUN_DA,
//    2,
                                        "dckAc2wbedgiH48D0MbpP6iEIXP9XrjEUsMVZb83IvxJxrg8yppSxdlgQ96J2KVMXivAb1e3d4_JAohTssixwSQw",
//    "GZYDGroupChat",
//    "",
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YUN_DA.getSecret(),
                                        WarehouseMsgKDConfEnum.JG_CW_KD_YUN_DA.getToken(),
                                        null, null)
                        )));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.HF_DP.getCode(), //合肥-肥西（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.HF_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//合肥仓（冻品）审单对接群
                                "mExel2BLV5yX62NDIE2lr4KXVgk9rpMq",
                                WarehouseMsgSDConfEnum.HF_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.HF_DP_SD.getToken(),
//    "SECa00b70bcf2d9e339d899e4449b8e95ffbfe042759b7c83294f1e70a5476d4c1b",
//    "46653a24eda213db1d93fa75b78a865b702f8c7d662345089d7dee66a58ddde5",

                                null, null),
                        Arrays.asList(new WarehouseExpressDeliveryConfig(//台肥仓（冻品）快递售后群（统一）
                                WarehouseMsgKDConfEnum.HF_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.HF_DP_KD.getPlatform(),
//    ExpressDeliveryUtil.UNKNOWN,
//    1,
                                "m9bN7RYPWdXg9GkRIodvProYWZd1wyK0",

//    "SEC5e61e55f743d8952cba699be732e43eaf7bdd12da0b559c9591454f7b76bcd67",
//    "dd6f2fe2186a84b85852025680db4ad2573240bb9481c12f9cf3f8802a0af44e",
                                WarehouseMsgKDConfEnum.HF_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.HF_DP_KD.getToken(),
                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.TZ_DP.getCode(), //济南-天泽（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.TZ_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//天泽仓（冻品）审单对接群
                                "dpYLaezmVNgO3NE5iZqj05oRJrMqPxX6",
//    "SEC02bc013b8a145ac6f7eec43b7e75eeafb9267af06105c2d33572a49a6a9594f7",
//    "e827de0a3c7c23763b7aa34e5a2750bd9d48e8a01fdd10e658eb674b11ef3bfb",
                                WarehouseMsgSDConfEnum.TZ_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.TZ_DP_SD.getToken(),
                                null, null),
                        Arrays.asList(new WarehouseExpressDeliveryConfig(//天泽仓（冻品）快递售后群（统一）
//    ExpressDeliveryUtil.UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.TZ_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.TZ_DP_KD.getPlatform(),
                                "20eMKjyp81ONekDKudwzbYd6VxAZB1Gv",

//    "SEC213971c59ea21362ab08113d632268a413aabbeb3c40de9f79b64be019d5c4a0",
//    "49014cfc32833bf3e1bf99ada174ec3ce018f1aee533ef1e7b2a21f82e803e0b",
                                WarehouseMsgKDConfEnum.TZ_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.TZ_DP_KD.getToken(),
                                null, null))
                ));


        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.SH_DP.getCode(), //上海-上海（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.SH_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//上海仓 （冻品）审单对接群
                                "dQPGYqjpJYm0ALeNidOyzp4AJakx1Z5N",
                                WarehouseMsgSDConfEnum.SH_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.SH_DP_SD.getToken(),
//    "SEC0c1e7682f88bb4cb7166ecd3fe715ae005a626ef41595d04af62d069910e9d23",
//    "f608f1d572bb78926f993125aaa8d84b6d49f1c5df50bcd01d1a3c2912d5f49b",
                                null, null),
                        Arrays.asList(new WarehouseExpressDeliveryConfig(//上海仓（冻品）快递售后群
//    ExpressDeliveryUtil.UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.SH_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.SH_DP_KD.getPlatform(),
                                "dQPGYqjpJYm0ALeNidxab5q1Jakx1Z5N",
                                WarehouseMsgKDConfEnum.SH_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.SH_DP_KD.getToken(),
//    "SECc3abcdd288e118ab8fb5058446575207c4ac39b7d790aca3fdd91d0af533ee14",
//    "907e7b99a154cd1b93e6b5eee12bd1752c273ab36b76087d64964494245210a4",
                                null, null))
                ));


        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.DX_DP.getCode(), //广州-德信（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.DX_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//德信仓 （冻品）审单对接群
                                "Gl6Pm2Db8DemzxdRFqo1m2o2WxLq0Ee4",
                                WarehouseMsgSDConfEnum.DX_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.DX_DP_SD.getToken(),
//    "SEC65d0625b209020cc90739c903a5996c0769fa8e2688819ae4cfcd71e382f6317",
//    "4c3acb26d958853d57f73325e5bd449904b9addc3c12efbee8914fe7242cdab5",
                                null, null),
                        Arrays.asList(new WarehouseExpressDeliveryConfig(//德信仓（冻品）快递售后群
//    ExpressDeliveryUtil.UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.DX_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.DX_DP_KD.getPlatform(),

                                "jb9Y4gmKWrblnwA4UaNdEdNgWGXn6lpz",
                                WarehouseMsgKDConfEnum.DX_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.DX_DP_KD.getToken(),
//    "SEC02533e52d5bf330638e1158784ef3fa150cfde8ac2e385e3d8adff522f0d820e",
//    "99e098e1c67bfb7693156757a7a56f1d856f37df91b58dc0ff496347a19d6ef1",

                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.JX_CW.getCode(),//江西-南昌（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.JX_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//江西仓（常温）审单对接群

                                "amweZ92PV6yZQ2kgIdjna5ZzWxEKBD6p",
                                WarehouseMsgSDConfEnum.JX_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.JX_CW_SD.getToken(),
//    "SEC6bfb84740d75d8efeaf69aeeb97747465d7c111dc7c34f90ebc7fa89d9770bb9",
//    "e6eaeec4d7e8d06c6f80849f459e2d032b938b617c22fb44246485bc6c9005bd",
                                null, null)
                        , Arrays.asList(new WarehouseExpressDeliveryConfig(//江西仓（常温）快递售后群（圆通)
                                WarehouseMsgKDConfEnum.JX_CW_KD_YTO.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.JX_CW_KD_YTO.getPlatform(),
//    YTO,
//    1,
                                "YndMj49yWjmvkeaxi0Kr5K9Y83pmz5aA",
                                WarehouseMsgKDConfEnum.JX_CW_KD_YTO.getSecret(),
                                WarehouseMsgKDConfEnum.JX_CW_KD_YTO.getToken(),
//    "SEC56b4084a06e60b05406b4a49ddb660e46061c21ab2282694305436c567351cb9",
//    "87bf9ed52b5c60b6a340aa5cfc7c260875cf1b15a542429fe660062d2cf72bcb",
                                null, null),
                        new WarehouseExpressDeliveryConfig(//江西仓（常温）快递售后群（中通）
                                WarehouseMsgKDConfEnum.JX_CW_KD_ZTO.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.JX_CW_KD_ZTO.getPlatform(),
//    ZTO,
//    1,
                                "oP0MALyR8kb9XAmOUE13dNmXJ3bzYmDO",
                                WarehouseMsgKDConfEnum.JX_CW_KD_ZTO.getSecret(),
                                WarehouseMsgKDConfEnum.JX_CW_KD_ZTO.getToken(),
//    "SECb2eb67a58fea92969487daa296a9536063fb35faa743df99c09d344bc1a86873",
//    "c18019d56f6c24f4a9ff6ded03e67823c63d1e8adff761ed6e01152461e7bfd9",

                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CS_DP.getCode(),//长沙-中通（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CS_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//长沙仓（冻品）审单对接群
                                "YQBnd5ExVE1mZxG0TkYoBQoNVyeZqMmz",
//    "SEC29cb16689d420846a5b9bc319c2b33c5e0046097e9ec45ed9c255552300cee2f",
//    "8ed9de0a29deae71b5adf2cc1b2542a2ebdd1d863b0ee96c42ca948a76a5cd55",
                                WarehouseMsgSDConfEnum.CS_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CS_DP_SD.getToken(),
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//长沙仓（冻品）快递售后群（统一）
//    UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.CS_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.CS_DP_KD.getPlatform(),
                                "R1zknDm0WRkePAE4t9rNjN5EVBQEx5rG",
                                WarehouseMsgKDConfEnum.CS_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.CS_DP_KD.getToken(),
//    "SEC098707457239ad8f5644fed315bb2de2f8c2f711820a2fd08f48651295f8bfdd",
//    "ecdb4ce675945a909f87f8e266065ebf1f8d3e6d1ff0557a563657f46c44852d",
                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.CS_CW.getCode(), //湖南-长沙（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.CS_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//长沙仓（常温）审单对接群
                                "R1zknDm0WRkePAE4t94Y4BbBVBQEx5rG",
//    "SECfde84f7f2dd69c99b6908fafb2aa5144c5db93c8177c203f956589d159eba57c",
//    "44fa9a1f188fd78a96f8a5cb9553291344a31f1c4a1e9a68169bdd85fea9d1b4",
                                WarehouseMsgSDConfEnum.CS_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.CS_CW_SD.getToken(),
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//长沙仓（常温）快递售后群（统一）
//    UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.CS_CW_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.CS_CW_KD.getPlatform(),
                                "vy20BglGWOMOykAqTl2wApeAJA7depqY",
//    "SEC1e32020d251b1ce7fa59cef98f8ac79386f990ebc4196d60d34bd5e7f3d90008",
//    "d82616b734a61bcfc6aae27b6bd5bcb70330b47f24210375b6185cd01818736d",
                                WarehouseMsgKDConfEnum.CS_CW_KD.getSecret(),
                                WarehouseMsgKDConfEnum.CS_CW_KD.getToken(),
                                null, null))
                ));


        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.YW_CW.getCode(),//浙江-义乌（常温仓）
                new WarehouseConfigEntity(WarehouseConfEnum.YW_CW.getRoomTemperatureType(),//常温
                        new WarehouseInterceptionConfig(//义乌仓 （常温）审单对接群
                                "kDnRL6jAJMDAYjEwHDplENkLVyMoPYe1",
//    "SECe47c325f8d7a780f4dd40ad9dfc84eb24d962f4d4b55e323b0fb4ee23d514d91",
//    "45cb669c31d7911fbfb678f95c9bc377e92370b9129922bcfdbd1045a2bbb460",
                                WarehouseMsgSDConfEnum.YW_CW_SD.getSecret(),
                                WarehouseMsgSDConfEnum.YW_CW_SD.getToken(),
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//义乌仓 （常温）快递售后群（统一）
//    UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.YW_CW_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.YW_CW_KD.getPlatform(),
                                "kDnRL6jAJMDAYjEwHDNBgKPYVyMoPYe1",
                                WarehouseMsgKDConfEnum.YW_CW_KD.getSecret(),
                                WarehouseMsgKDConfEnum.YW_CW_KD.getToken(),
//    "SECc3f3b364885974c38e832e8a7651845a81422f7e79e97e1979fc66916b0eff02",
//    "3429beb9ba26135ed6193d0db68732c641e16d3edd6bd65dd779b16dc9a8eca9",
                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.SY_DP.getCode(), //沈阳-天泽（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.SY_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//沈阳仓（冻品）审单对接群
                                "ZX6GRezwJlyDpZnPInxORYKM8dqbropQ",
                                WarehouseMsgSDConfEnum.SY_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.SY_DP_SD.getToken(),
//    "SECac80969d041ff8892ac15b70fd20b4491f1756a2c3b8b2f32acff8991a2936b2",
//    "50d1f1dbd99d18a8a80998bc75ab78cd30aa96a6f9fe5db9ab0716c2f0f9aa02",
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//沈阳仓 （冻品）快递售后群
//    UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.SY_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.SY_DP_KD.getPlatform(),
                                "XPwkYGxZV3yXoPMvIE7aKozo8AgozOKL",
                                WarehouseMsgKDConfEnum.SY_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.SY_DP_KD.getToken(),
//    "SECacba4eed59b688fd3e4f7eff889923b1b4aa639a19d84d5b6f7b351a9a591d34",
//    "17254730ade1d35fda71e320b77df73d6a082e055251675514395ee16f4de859",
                                null, null))
                ));

        WAREHOUSE_INTERCEPT_CONFIG.put(WarehouseConfEnum.WH_DP.getCode(), //湖北-武汉（冻品仓）
                new WarehouseConfigEntity(WarehouseConfEnum.WH_DP.getRoomTemperatureType(),//冻品
                        new WarehouseInterceptionConfig(//湖北-武汉（冻品仓）审单对接群
                                "dpYLaezmVNgO3NE5iZ509Q41JrMqPxX6",
                                WarehouseMsgSDConfEnum.WH_DP_SD.getSecret(),
                                WarehouseMsgSDConfEnum.WH_DP_SD.getToken(),
//    "SEC4ea92f914a94e250a53386bbc52e337e5b329bacefafb4941763af706db45b66",
//    "c8b2af9667d429ca6bf44cd46487639f4f914847c842d9b9af78321e2895fa82",
                                null, null),
                        Collections.singletonList(new WarehouseExpressDeliveryConfig(//湖北-武汉（冻品仓）快递售后群
//    UNKNOWN,
//    1,
                                WarehouseMsgKDConfEnum.WH_DP_KD.getExpressDeliveryType(),
                                WarehouseMsgKDConfEnum.WH_DP_KD.getPlatform(),
                                "Obva6QBXJw6lYwAMFlpXkG0RVn4qY5Pr",
                                WarehouseMsgKDConfEnum.WH_DP_KD.getSecret(),
                                WarehouseMsgKDConfEnum.WH_DP_KD.getToken(),
//    "SEC7c5c1df411b824dcb4e2a6612921ed6c7c4763189e03df6297f5604262a289ef",
//    "e5b9204fd30a5059b4d99bd0bb1b84072ae5e8a1265f705189d1adf5c3f23916",
                                null, null))
                ));

    }


    /**
     * 判断当前时间
     *
     * @param dateTime
     * @param hour
     * @return
     */
    public static boolean isEightOClock(LocalDateTime dateTime, int hour) {
        return dateTime.getHour() == hour &&
                dateTime.getMinute() == 0 &&
                dateTime.getSecond() == 0 &&
                dateTime.getNano() == 0;
    }

    //   @Scheduled(cron = "0 0/10 8-18 * * ?", zone = "Asia/Shanghai")
    public void scheduledTasks() {
        refundDataAcquisition();
    }

    /**
     * 获取库内拦截数据
     */
    private void refundDataAcquisition() {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime endTime = today;
        endTime = endTime.minusSeconds(2);
//    endTime=endTime.minusNanos(10000000);
        LocalDateTime startTime = null;
//    String sheetId=sheetIdPrefix.concat(today.format(FORMATTERM));
        String sheetId = today.format(FORMATTER_YYYY_MM);
        boolean isEightAM = isEightOClock(endTime, startIntervalTime);
        if (isEightAM) {
            Integer hour = startIntervalTime + (24 - 18);
            startTime = today.minusHours(hour);
        } else {
            startTime = endTime.minusMinutes(intervalTime);
        }
        String dayStr = FORMATTER.format(today);
        List<SalesStockoutResponse.OrderInfoDto> findOrders = findOrders(startTime, endTime, findStatus);
        Map<String, List<SalesStockoutResponse.OrderInfoDto>> WAREHOUSE_NO_ORDER = findOrders.stream().
                filter(o -> {
                            if (o.getRefundStatus() == 0) {
                                return false;
                            }
                            if (o.getRefundStatus() == 2) {
                                return o.getDetailList().stream().noneMatch(d -> d.getRefundStatus() != 2 && d.getRefundStatus() != 5);
                            }
                            return true;
                        }
                ).collect(Collectors.groupingBy(SalesStockoutResponse.OrderInfoDto::getWarehouseNo));
        if (true) {
            return;
        }
        Set<String> warehouseNos = WAREHOUSE_NO_ORDER.keySet().stream().filter(WAREHOUSE_NO_ORDER::containsKey).collect(Collectors.toSet());
        for (String warehouseNo : warehouseNos) {
            List<Integer> findStatusList = new ArrayList<>(reviewedStatus);
            findStatusList.addAll(shippedStatus);
            //所有订单
            List<SalesStockoutResponse.OrderInfoDto> allOrders = WAREHOUSE_NO_ORDER.get(warehouseNo).stream().filter(e -> findStatusList.contains(e.getStatus())).collect(Collectors.toList());
            //已发货
            List<SalesStockoutResponse.OrderInfoDto> shippedData = allOrders.stream().filter(order -> shippedStatus.contains(order.getStatus())).collect(Collectors.toList());
            //未发货
            List<SalesStockoutResponse.OrderInfoDto> reviewedOrders = allOrders.stream().filter(order -> reviewedStatus.contains(order.getStatus())).collect(Collectors.toList());
            //获取仓库消息配置
            WarehouseConfigEntity dataItem = WAREHOUSE_INTERCEPT_CONFIG.get(warehouseNo);
            //获取仓库类型 1冻品 2常温
            String type = dataItem.getType();
            //库内拦截是 已发货 未揽收 已退款或是申请退款  //未发货  申请退款  已退款 部分退款 （常温和冻品）
            //在途拦截是 已发货 已揽收 已退款或是申请退款 只有常温
            //库内拦截
            List<List<String>> libraryInterceptionValues = new ArrayList<>();
            if (!reviewedOrders.isEmpty()) {//未发货
                libraryInterceptionValues.addAll(warehouseDataDispose(reviewedOrders));
            }

            List<List<String>> transitInterceptionValues = new ArrayList<>();
            if (!shippedData.isEmpty()) {//已发货
                Map<Integer, List<SalesStockoutResponse.OrderInfoDto>> SEND_TYPE_DATAS = shippedData.stream().map(sd -> {
                    ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(sd.getLogisticsNo());
                    List<ExpressDeliveryTrack> tracks = result.getTracks();
                    sd.setIfFind(result.getSucceed());
                    if (sd.getIfFind() && !tracks.isEmpty()) {
                        sd.setCollectionTime(tracks.get(0).getScanDateStr());
                    }
                    sd.setInvoiceType(result.getTracks().isEmpty() ? 0 : 1);
                    return sd;
                }).filter(SalesStockoutResponse.OrderInfoDto::getIfFind).collect(Collectors.groupingBy(SalesStockoutResponse.OrderInfoDto::getInvoiceType));
                List<List<String>> notCollected = warehouseDataDispose(SEND_TYPE_DATAS.get(0));

                if (!notCollected.isEmpty()) {
                    libraryInterceptionValues.addAll(notCollected);
                }
                //在途拦截
                if (ObjectUtil.equals(type, roomTemperatureType)) {
                    List<List<String>> collected = expressDeliveryDataDispose(SEND_TYPE_DATAS.get(1));
                    if (!collected.isEmpty()) {
                        transitInterceptionValues.addAll(collected);
                    }
                }
            }

            if (!libraryInterceptionValues.isEmpty()) {//库内拦截
                WarehouseInterceptionConfig libraryInterceptionParam = dataItem.getLibraryInterceptionConfig();
                String workbookId = libraryInterceptionParam.getWorkbookId();
                String secret = libraryInterceptionParam.getSecret();
                String token = libraryInterceptionParam.getToken();
                List<String> atMobiles = libraryInterceptionParam.getAtMobiles();
                List<String> atUserIds = libraryInterceptionParam.getAtUserIds();
                updateAiExcelSendMsg(1, workbookId, secret, token, atMobiles, atUserIds, libraryInterceptionValues, sheetId, warehouseHeaderValues, warehouseMsgTitle, warehouseMsgTemplate, warehouseEndingContent, updateBatchSize);
            }

            if (!transitInterceptionValues.isEmpty()) {//在途拦截
                List<WarehouseExpressDeliveryConfig> transitInterceptionConfigs = dataItem.getTransitInterceptionConfigs();
                Map<String, WarehouseExpressDeliveryConfig> ED_TYPE_CONFIG = transitInterceptionConfigs.stream().collect(Collectors.toMap(WarehouseExpressDeliveryConfig::getExpressDeliveryType, Function.identity()));
                Map<String, List<List<String>>> EXPRESS_DELIVERY_TYPE_CONFIG = transitInterceptionValues.stream().collect(Collectors.groupingBy(o -> judgeExpressDeliveryType(o.get(0))));
                EXPRESS_DELIVERY_TYPE_CONFIG.remove(UNKNOWN);
                for (String key : EXPRESS_DELIVERY_TYPE_CONFIG.keySet()) {
                    List<List<String>> typeLists = EXPRESS_DELIVERY_TYPE_CONFIG.get(key);
                    WarehouseExpressDeliveryConfig warehouseExpressDeliveryConfigs = ED_TYPE_CONFIG.get(key);
                    if (ObjectUtil.isNotNull(warehouseExpressDeliveryConfigs)) {
                        Integer platform = warehouseExpressDeliveryConfigs.getPlatform();
                        String workbookId = warehouseExpressDeliveryConfigs.getWorkbookId();
                        String secret = warehouseExpressDeliveryConfigs.getSecret();
                        String token = warehouseExpressDeliveryConfigs.getToken();
                        List<String> atMobiles = warehouseExpressDeliveryConfigs.getAtMobiles();
                        List<String> atUserIds = warehouseExpressDeliveryConfigs.getAtUserIds();

//         updateDocumentSending(platform,workbookId,secret,token,atMobiles,atUserIds,typeLists,sheetId,expressDeliveryHeaderValues,expressDeliveryMsgTitle,expressDeliveryMsgTemplate,expressDeliveryEndingContent,expressDeliveryRangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit,keyTemplate);
                        updateAiExcelSendMsg(platform, workbookId, secret, token, atMobiles, atUserIds, typeLists, sheetId, expressDeliveryHeaderValues, expressDeliveryMsgTitle, expressDeliveryMsgTemplate, expressDeliveryEndingContent, updateBatchSize);
                    }
                }
            }
        }
    }

    /**
     * 订单列表处理仓库群
     */
    public List<List<String>> warehouseDataDispose(List<SalesStockoutResponse.OrderInfoDto> data) {
        return data.stream().map(o -> {
            String srcTradeNo = o.getSrcTradeNo();
            String orderNo = o.getOrderNo();
            String tradeNo = o.getTradeNo();
            String logisticsNo = o.getLogisticsNo();
            String created = DateUtil.toDateToStr(o.getCreated());
            String consignTime = DateUtil.toDateToStr(o.getConsignTime());
            String collectionTime = Optional.ofNullable(o.getCollectionTime()).orElse("");
            return Arrays.asList(srcTradeNo, orderNo, tradeNo, logisticsNo, created, consignTime, collectionTime);
        }).collect(Collectors.toList());
    }

    /**
     * 快递群
     *
     * @param data
     * @return
     */
    public List<List<String>> expressDeliveryDataDispose(List<SalesStockoutResponse.OrderInfoDto> data) {
        return data.stream().map(o -> {
            String srcTradeNo = o.getSrcTradeNo();
            String orderNo = o.getOrderNo();
            String tradeNo = o.getTradeNo();
            String logisticsNo = o.getLogisticsNo();
            return Arrays.asList(srcTradeNo, orderNo, tradeNo, logisticsNo);
        }).collect(Collectors.toList());
    }

    /**
     * String findStatus="110";已完成 已审核
     *
     * @param startTime
     * @param endTime
     * @param findStatus
     */
    public static List<SalesStockoutResponse.OrderInfoDto> findOrders(LocalDateTime startTime, LocalDateTime endTime, String findStatus) {
        List<String> times = getHourlyTimesBetween(startTime, endTime);
        List<SalesStockoutResponse.OrderInfoDto> orders = new ArrayList<>();
        Integer pageSize = 200;
        for (int i = 1; i < times.size(); i++) {
            String searchStartTime = times.get(i - 1);
            String searchEndTime = times.get(i);
            SalesStockoutResponse salesStockoutResponse = WDTUtil.queryWithDetail(searchStartTime, searchEndTime, STATUS_TYPE_CONSIGNED, findStatus, pageSize, 0);
            orders.addAll(salesStockoutResponse.getOrderList());
            int totalCount = salesStockoutResponse.getTotal() - pageSize;//剩余订单数量
            if (totalCount > 0) {
                int totalPages = (totalCount + pageSize - 1) / pageSize;
                int currentPageSize = 0;
                for (int pageNo = 1; pageNo <= totalPages; pageNo++) {
                    currentPageSize = totalCount - pageSize * (pageNo - 1);
                    if (currentPageSize > pageSize) {
                        currentPageSize = pageSize;
                    }
                    salesStockoutResponse = WDTUtil.queryWithDetail(searchStartTime, searchEndTime, STATUS_TYPE_CONSIGNED, findStatus, currentPageSize, pageNo);
                    orders.addAll(salesStockoutResponse.getOrderList());
                }
            }
        }
        orders = new ArrayList<>(orders.stream().map(order -> new AbstractMap.SimpleEntry<>(order.getTradeId(), order)) // 创建一个复合键（例如"name:age"）和person的映射项
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (existing, replacement) -> existing)) // 使用Map去重，保留第一个出现的元素（基于复合键）
                .values());
        return orders;
    }

    /**
     * 获取两个时间中的时间条件
     *
     * @param start
     * @param end
     * @return
     */
    public static List<String> getHourlyTimesBetween(LocalDateTime start, LocalDateTime end) {
        // 参数校验
        if (start == null || end == null) {
            throw new IllegalArgumentException("开始时间和结束时间不能为null");
        }
        if (start.isAfter(end)) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }

        Duration interval = Duration.ofMinutes(intervalTime);
        // 计算总间隔数（包含起始点和结束点）
        long fullIntervals = Duration.between(start, end).toMinutes() / intervalTime;
        long numberOfIntervals = fullIntervals + 1;

        // 如果结束时间不是半小时整点，需要额外加一个时间点
        if (Duration.between(start, end).toMinutes() % intervalTime != 0) {
            numberOfIntervals++;
        }

        return Stream.iterate(start, time -> time.plus(interval))
                .limit(numberOfIntervals)
                .map(FORMATTER::format)
                .collect(Collectors.toList());
    }


//
//    /**
//     *     * 获取上次更新的下标
//     *      * String workbookId="Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr";
//     *      * String sheetId="s1";
//     *      * @param rangeAddressKey
//     * @param rangeAddressKey
//     * @param workbookId
//     * @param sheetId
//     * @return
//     */
//    public Integer ddOptimizeTable(String rangeAddressKey,String workbookId,String sheetId,List<String> headerValues) {
//        String currentSubscriptStr = redisService.getString(rangeAddressKey);
//        Integer currentSubscript=1;
//        if (StringUtils.isBlank(currentSubscriptStr)){
//            List<String>findSheets=DDUtil.getSheets(workbookId).getJSONArray("value").stream().map(val->{
//            JSONObject vm=(JSONObject)val;return vm.getString("name");}).filter(name->name.equals(sheetId)).collect(Collectors.toList());
//            if(!findSheets.isEmpty()){
//                Integer startIndex=currentSubscript;
//                Integer endIndex=startIndex+readBatchSize;
//                currentSubscript=0;
//                for (int i = 0; i <100; i++) {
//                    String rangeAddress=String.format(warehouseRangeAddressTemplate,startIndex,endIndex);
//                    JSONObject rsData=JSONObject.parseObject(DDUtil.readSheets(workbookId,sheetId,rangeAddress));
//                    long rssData=rsData.getJSONArray("values").stream().map(v->(List<Object>)v).filter(v->StringUtils.isNotBlank(v.get(0).toString())).count();
//                    currentSubscript= Math.toIntExact(currentSubscript + rssData );
//                    if(rssData==0){break;}
//                    startIndex=endIndex+1;
//                    endIndex=endIndex+readBatchSize;
//                }
//                redisService.setWithExpire(rangeAddressKey,currentSubscript.toString(),dataSaveDays,timeUnit);
//                }else{
//                 DDUtil.createSheets(workbookId,sheetId);
//                 String rangeAddress=String.format(warehouseRangeAddressTemplate,currentSubscript,currentSubscript);
//                 DDUtil.updateRange(workbookId,sheetId,rangeAddress,Collections.singletonList(headerValues));
//                redisService.setWithExpire(rangeAddressKey,currentSubscript.toString(),dataSaveDays,timeUnit);
//                }
//        }else {
//            currentSubscript=Integer.parseInt(currentSubscriptStr);
//        }
//        return currentSubscript;
//    }
//
//    /**
//     *     * 获取上次更新的下标
//     *      * String workbookId="Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr";
//     *      * String sheetId="s1";
//     *      * @param rangeAddressKey
//     * @param workbookId
//     * @param sheetId
//     * @return
//     */
//    public JSONObject qwOptimizeTable(String workbookId,String sheetId,List<String> headerValues) {
//        SpreadSheetGetSheetPropertiesResponse spreadSheetGetSheetProperties = spreadSheetGetSheetProperties(workbookId);
//        String dateStr=sheetId;
//        Integer rowCount=1;
//        List<SpreadSheetGetSheetPropertiesItem>singleton= spreadSheetGetSheetProperties.getProperties().stream().filter(prp -> ObjectUtil.equal(prp.getTitle(), dateStr)).collect(Collectors.toList());
//        if(!singleton.isEmpty()){
//            sheetId=singleton.get(0).getSheetId();
//            rowCount=singleton.get(0).getRowCount();
//        }else{
//            shade.com.alibaba.fastjson2.JSONObject bsResult = batchUpdateSpreadsheet(workbookId, createAddSheetRequest(dateStr,600,10));
//            sheetId = bsResult.getJSONArray("responses").getJSONObject(0).getJSONObject("add_sheet_response").getJSONObject("properties").getString("sheet_id");
//            shade.com.alibaba.fastjson2.JSONObject updateRequest = batchUpdateSpreadsheet(workbookId,createUpdateSheetRequest(sheetId, 0, 0, Collections.singletonList(headerValues)));
//            rowCount=1;
//        }
//        JSONObject param = new JSONObject();
//        param.put("sheetId",sheetId);
//        param.put("rowCount",rowCount);
//        return param;
//    }
//
//    /**
//     * 出库单列表转参数
//     * @param workbookId
//     * @param sheetId
//     * @param values
//     * @param currentSubscript
//     */
//    public void qwImportValuesData(String workbookId,String sheetId,List<List<String>>values,Integer currentSubscript){
//        WeChatUtil.batchUpdateSpreadsheetRecord(workbookId,sheetId,currentSubscript,values);
//    }
//    /**
//     * 出库单列表转参数
//     * @param workbookId
//     * @param sheetId
//     * @param values
//     * @param currentSubscript
//     * @param rangeAddressKey
//     */
//    public void ddImportValuesData(String workbookId,String sheetId,List<List<String>>values,Integer currentSubscript,String rangeAddressKey){
//        int totalSize = values.size();
//        Integer startIndex=currentSubscript;
//        Integer endIndex=startIndex;
//        for (int start = 0; start < totalSize; start += updateBatchSize) {
//            int end = Math.min(start + updateBatchSize, totalSize);
//            List<List<String>>batchValues=values.subList(start, end);
//            startIndex=endIndex+1;
//            endIndex=startIndex+batchValues.size()-1;
//            String rangeAddress=String.format(warehouseRangeAddressTemplate,startIndex,endIndex);
//            DDUtil.updateRange(workbookId,sheetId,rangeAddress,batchValues);
//        }
//        redisService.setWithExpire(rangeAddressKey,endIndex.toString(),dataSaveDays,timeUnit);
//    }
////    /**
////     * 获取上次的下标并导入
////     * @param param
////     * @param values
////     * @param sheetId
////     */
////    private void getInsertLocationUpdates(Map<String,String>param,List<List<String>>values,String sheetId){
////        String workbookId = param.get("workbookId");
////        String secret = param.get("secret");
////        String token = param.get("token");
////        String rangeAddressKey=String.format(keyTemplate,workbookId,sheetId);
////        Integer currentSubscript=optimizeTable(rangeAddressKey,workbookId,sheetId);
////        importValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey);
////        String content=values.stream().map(v->"原始单号："+v.get(0)+" ;出库单号："+v.get(1)+" ;物流公司："+v.get(2)+" ;物流单号："+v.get(3)).collect(Collectors.joining("\n"));
////        DDUtil.sendMessageWebhook(secret,token,content);
////    }
////    private void getInsertLocationUpdates(WarehouseInterceptionParam param,List<List<String>>values,String sheetId){
////        String workbookId = param.getWorkbookId();
////        String secret = param.getSecret();
////        String token = param.getToken();
////        String rangeAddressKey=String.format(keyTemplate,workbookId,sheetId);
////        Integer currentSubscript=ddOptimizeTable(rangeAddressKey,workbookId,sheetId);
////        ddImportValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey);
////        String content="退款快递拦截通知-测试阶段".concat("\n").concat(values.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"物流公司："+v.get(2)+"\n"+"物流单号："+v.get(3)).collect(Collectors.joining("\n")));
////        DDUtil.sendMessageWebhook(secret,token,content);
////    }
//
//    private void getInsertLocationUpdates(WarehouseInterceptionConfig param,List<List<String>>values,String sheetId,List<String> headerValues){
//        String workbookId = param.getWorkbookId();
//        String secret = param.getSecret();
//        String token = param.getToken();
//        List<String> atMobiles = param.getAtMobiles();
//        List<String> atUserIds = param.getAtUserIds();
//        String rangeAddressKey=String.format(keyTemplate,workbookId,sheetId);
////        Integer currentSubscript=ddOptimizeTable(rangeAddressKey,workbookId,sheetId,headerValues);
//        Integer currentSubscript = DDUtil.optimizeTable(rangeAddressKey, workbookId, sheetId, expressDeliveryRangeAddressTemplate, headerValues, updateBatchSize, dataSaveDays, timeUnit);
//        DDUtil.importValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey,expressDeliveryRangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit);
////        ddImportValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey);
////        String content="退款库内拦截-测试阶段".concat("\n").concat(values.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"物流公司："+v.get(2)+"\n"+"物流单号："+v.get(3)).collect(Collectors.joining("\n")));
////        String toLinkUrl=String.format(ddLinkUrl,workbookId);
////        content=content.concat("\n").concat(toLinkUrl);
////        DDUtil.sendMessageWebhook(secret,token,content,atUserIds,atMobiles);
//        List<List<List<String>>> partitionValues = Lists.partition(values, 9);
//        for(int i=0;i<partitionValues.size();i++){
//            List<List<String>>pv=partitionValues.get(i);
//            String content="订单未发仓内拦截通知-测试阶段".concat("\n").concat(pv.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"订单编号："+v.get(2)+"\n"+"物流单号："+v.get(3)+"\n"+"创建时间："+v.get(4)+"\n"+"发货时间："+v.get(5)+"\n"+"揽收时间："+v.get(6)).collect(Collectors.joining("\n")));
//            if(i==partitionValues.size()-1){
//                content=content.concat("\n").concat(String.format(ddLinkUrl,workbookId));
//            }
//            content=content.concat("\n").concat("处理类型：订单未发运，终止出库，退换单请及时入库。");
//            DDUtil.sendMessageWebhook(secret,token,content,atUserIds,atMobiles);
//        }
//    }
//    private void getDDInsertLocationUpdates(WarehouseExpressDeliveryConfig param,List<List<String>>values,String sheetId,List<String> headerValues){
//        String workbookId = param.getWorkbookId();
//        String secret = param.getSecret();
//        String token = param.getToken();
//        List<String> atMobiles = param.getAtMobiles();
//        List<String> atUserIds = param.getAtUserIds();
//        String rangeAddressKey=String.format(keyTemplate,workbookId,sheetId);
////        Integer currentSubscript=ddOptimizeTable(rangeAddressKey,workbookId,sheetId,headerValues);
////        qwImportValuesData(workbookId,sheetId,values,currentSubscript);
//        Integer currentSubscript = DDUtil.optimizeTable(rangeAddressKey, workbookId, sheetId, expressDeliveryRangeAddressTemplate, headerValues, updateBatchSize, dataSaveDays, timeUnit);
//        DDUtil.importValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey,expressDeliveryRangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit);
////        String content="退款在途拦截-测试阶段".concat("\n").concat(values.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"物流公司："+v.get(2)+"\n"+"物流单号："+v.get(3)).collect(Collectors.joining("\n")));
////        String toLinkUrl=String.format(ddLinkUrl,workbookId);
////        content=content.concat("\n").concat(toLinkUrl);
////        DDUtil.sendMessageWebhook(secret,token,content,atUserIds,atMobiles);
//        List<List<List<String>>> partitionValues = Lists.partition(values, 9);
//        for(int i=0;i<partitionValues.size();i++){
//            List<List<String>>pv=partitionValues.get(i);
//            String content="退款在途拦截-测试阶段".concat("\n").concat(pv.stream().
//            map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"订单编号："+v.get(2)+"\n"+"物流单号："+v.get(3)).collect(Collectors.joining("\n")));
//            if(i==partitionValues.size()-1){
//                content=content.concat("\n").concat(String.format(ddLinkUrl,workbookId));
//            }
//            content=content.concat("\n").concat("处理类型：拦截退回");
//            DDUtil.sendMessageWebhook(secret,token,content,atUserIds,atMobiles);
//        }
//
//    }
//
//    /**
//     *   String result = String.format(keyTemplate,strings.toArray())
//     * @param param
//     * @param values
//     * @param sheetId
//     * @param headerValues
//     */
//    private void getQwInsertLocationUpdates(WarehouseExpressDeliveryConfig param,List<List<String>>values,String sheetId,List<String> headerValues){
//        String workbookId = param.getWorkbookId();
//        String secret = param.getSecret();
//        String token = param.getToken();
////        JSONObject qwotResult=qwOptimizeTable(workbookId,sheetId,headerValues);
//        shade.com.alibaba.fastjson2.JSONObject qwotResult = WeChatUtil.optimizeTable(workbookId, sheetId, headerValues);
//        Integer currentSubscript = qwotResult.getInteger("rowCount");
//        sheetId = qwotResult.getString("sheetId");
////        qwImportValuesData(workbookId,sheetId,values,currentSubscript);
//        WeChatUtil.importValuesData(workbookId,sheetId,values,currentSubscript);
////        Integer currentSubscript = WeChatUtil.optimizeTable(rangeAddressKey, workbookId, sheetId, rangeAddressTemplate, headerValues, updateBatchSize, dataSaveDays, timeUnit);
////        DDUtil.importValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey,rangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit);
////        String content=values.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"物流公司："+v.get(2)+"\n"+"物流单号："+v.get(3)+"\n").collect(Collectors.joining("\n"));
////        String toLinkUrl=String.format(qwLinkUrl,param.getToken());
////        content=content.concat("\n").concat(token);
////        WeChatUtil.sendTextMessage(secret,content,false);
//        List<List<List<String>>> partitionValues = Lists.partition(values, 8);
//        String content="退款在途拦截-测试阶段".concat("\n");
//        for(int i=0;i<partitionValues.size();i++){
//            List<List<String>>pv=partitionValues.get(i);
//            content=content.concat(pv.stream().map(v->"原始单号："+v.get(0)+"\n"+"出库单号："+v.get(1)+"\n"+"订单编号："+v.get(2)+"\n"+"物流单号："+v.get(3)).collect(Collectors.joining("\n")));
//            if(i==partitionValues.size()-1){
//                content=content.concat("\n").concat(Objects.requireNonNull(getDocumentShareUrl(workbookId)));
//            }
//            content=content.concat("\n").concat("处理类型：拦截退回");
//            WeChatUtil.sendTextMessage(secret,content,false);
//        }
//    }
//
//    private void qwUpdateDocumentSending(String workbookId,String secret,String token,List<String> atMobiles,List<String> atUserIds,List<List<String>>values,
//     String sheetId,List<String> headerValues,String msgTitle,String msgTemplate,String endingContent,String rangeAddressTemplate,Integer updateBatchSize,Integer dataSaveDays,TimeUnit timeUnit,String keyTemplate){

    /// /        String workbookId = param.getWorkbookId();
    /// /        String secret = param.getSecret();
    /// /        String token = param.getToken();
//        shade.com.alibaba.fastjson2.JSONObject qwotResult = WeChatUtil.optimizeTable(workbookId, sheetId, headerValues);
//        Integer currentSubscript = qwotResult.getInteger("rowCount");
//        sheetId = qwotResult.getString("sheetId");
//        WeChatUtil.importValuesData(workbookId,sheetId,values,currentSubscript);
//        List<List<List<String>>> partitionValues = Lists.partition(values, 8);
//        String content=msgTitle.concat("\n");
//        for(int i=0;i<partitionValues.size();i++){
//            List<List<String>>pv=partitionValues.get(i);
//            content=content.concat(pv.stream().map(cpv->String.format(msgTemplate,cpv.toArray())).collect(Collectors.joining("\n")));
//            content=content.concat("\n").concat(endingContent);
//            content=content.concat("\n").concat(Objects.requireNonNull(getDocumentShareUrl(workbookId)));
//            WeChatUtil.sendTextMessage(secret,content,false);
//        }
//    }
//
//
//    private void ddUpdateDocumentSending(String workbookId,String secret,String token,List<String> atMobiles,List<String> atUserIds,List<List<String>>values,String sheetId,
//    List<String> headerValues,String msgTitle,String msgTemplate,String endingContent,String rangeAddressTemplate,Integer updateBatchSize,Integer dataSaveDays,TimeUnit timeUnit,String keyTemplate){
//        String rangeAddressKey=String.format(keyTemplate,workbookId,sheetId);
//        Integer currentSubscript = DDUtil.optimizeTable(rangeAddressKey, workbookId, sheetId, rangeAddressTemplate, headerValues, updateBatchSize, dataSaveDays, timeUnit);
//        DDUtil.importValuesData(workbookId,sheetId,values,currentSubscript,rangeAddressKey,rangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit);
//        List<List<List<String>>> partitionValues = Lists.partition(values, 9);
//        for(int i=0;i<partitionValues.size();i++){
//             List<List<String>>pv=partitionValues.get(i);
//             String content=msgTitle.concat("\n\n").concat(
//             pv.stream().map(cpv->String.format(msgTemplate,cpv.toArray()).concat("\n")).collect(Collectors.joining("\n")));
//             content=content.concat("\n").concat(endingContent);
//             content=content.concat("\n").concat(String.format(ddLinkUrl,workbookId));
//             DDUtil.sendMessageWebhook(secret,token,content,atUserIds,atMobiles);
//        }
//    }


//    private void updateDocumentSending(Integer platform,String workbookId,String secret,String token,List<String> atMobiles,List<String> atUserIds,List<List<String>>values,
//     String sheetId,List<String> headerValues,String msgTitle,String msgTemplate,String endingContent,String rangeAddressTemplate,Integer updateBatchSize,Integer dataSaveDays,TimeUnit timeUnit,String keyTemplate){
//        //平台 1钉钉 2企业微信
//        if(ObjectUtil.equals(platform,1)){
//            DDUtil.updateDocumentSending(workbookId,secret,token,atMobiles,atUserIds,values,sheetId,headerValues,msgTitle,msgTemplate,endingContent,rangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit,keyTemplate);
//        }else {
//            WeChatUtil.updateDocumentSending(workbookId,secret,token,atMobiles,atUserIds,values,sheetId,headerValues,msgTitle,msgTemplate,endingContent,rangeAddressTemplate,updateBatchSize,dataSaveDays,timeUnit,keyTemplate);
//        }
//    }
    private void updateAiExcelSendMsg(Integer platform, String workbookId, String secret, String token, List<String> atMobiles, List<String> atUserIds, List<List<String>> values,
                                      String sheetId, List<String> headerValues, String msgTitle, String msgTemplate, String endingContent, Integer updateBatchSize) {
        //平台 1钉钉 2企业微信
        if (ObjectUtil.equals(platform, 1)) {
            DDUtil.updateAiExcelSendMsg(workbookId, secret, token, atMobiles, atUserIds, values, sheetId, headerValues, msgTitle, msgTemplate, endingContent, updateBatchSize);
        } else {
            WeChatUtil.updateAiExcelSendMsg(workbookId, secret, token, atMobiles, atUserIds, values, sheetId, headerValues, msgTitle, msgTemplate, endingContent, updateBatchSize);
        }
    }

}
